package com.alstudio.ui.module.main;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.Toast;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.mission.ALMissionManager;
import com.alstudio.module.xmpp.protocol.xmpp.ALXmppEventNotifyManager;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppConnectionState;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.config.BaseTitleActivityConfig;
import com.alstudio.ui.module.main.fragment.FriendsFragment;
import com.alstudio.ui.module.main.fragment.MeFragment;
import com.alstudio.ui.module.main.fragment.discovery.DiscoveryFragment;
import com.alstudio.ui.module.main.fragment.rank.MyRankInfoActivity;
import com.alstudio.ui.module.main.fragment.rank.RankFragment;
import com.alstudio.ui.module.main.item.MainBottomItem;
import com.alstudio.ui.module.props.PropsActivity;
import com.alstudio.ui.module.voip.BaoMiHuaActivity;
import com.alstudio.ui.module.voip.XieHouActivity;
import com.alstudio.utils.android.net.ALConnectionManager.ALConnectionType;
import com.alstudio.utils.asyncTask.ALAsycTask;
import com.alstudio.utils.asyncTask.ALAsyncTaskCallback;
import com.alstudio.utils.formater.time.ALTimeUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.mission.ALMissionHttpManager;
import com.alstudio.utils.mission.MissionInfo;
import com.alstudio.view.popwindow.ALPopWindowUtils;
import com.loovee.imaohu.R;
import com.readystatesoftware.viewbadger.BadgeView;

public class MainActivity extends TitleBarActivity implements OnClickListener,
		com.alstudio.utils.android.net.ALWifiManager.WifiStateChangedCallback {

	private interface BottomItemClickListener {
		public void onItemClick(int pos);
	}

	private BottomItemClickListener mBottomItemClickListener = new BottomItemClickListener() {

		@Override
		public void onItemClick(int pos) {
			// TODO Auto-generated method stub
			for (int i = 0; i < mainBottomItems.size(); i++) {
				if (pos == i) {
					mainBottomItems.get(i).setItemSelected(true);
				} else {
					mainBottomItems.get(i).setItemSelected(false);
				}
			}
			doChangeTab(pos);
		}
	};

	// 底栏布局
	private LinearLayout buttom_content_layout;

	// 底栏item文字
	private int[] bottomItemTxt = { R.string.TxtDiscovery, R.string.TxtRank,
			R.string.TxtBlank, R.string.TxtFriend, R.string.TxtMe };

	private int[] itemImgs = { R.drawable.find_tab_icon_01,
			R.drawable.find_tab_icon_01_press, R.drawable.find_tab_icon_02,
			R.drawable.find_tab_icon_02_press, -1, -1,
			R.drawable.find_tab_icon_03, R.drawable.find_tab_icon_03_press,
			R.drawable.find_tab_icon_04, R.drawable.find_tab_icon_04_press };
	private ArrayList<MainBottomItem> mainBottomItems = new ArrayList<MainBottomItem>();

	private DiscoveryFragment discoveryFragment;
	private RankFragment rankFragment;
	private FriendsFragment friendFragment;
	private MeFragment meFragment;
	private android.support.v4.app.FragmentTransaction ft;

	private final int TAB_DISCOVERY = 0;
	private final int TAB_RANK = 1;
	private final int TAB_FRIEND = 3;
	private final int TAB_ME = 4;
	private final int TAB_NONE = -1;
	private int currentTab = TAB_NONE;

	private boolean isShowIngSelectGender = false;

	private View discoverySelectView;
	private PopupWindow discoverySelectPopWindow;

	public enum DiscoveryRefreshType {
		TYPE_ALL, TYPE_FEMALE, TYPE_MALE,
	}

	private boolean inited = false;

	private boolean isEditInFriend = false;

	// 任务显示
	private BadgeView taskBadge;

	private MainBottomItem friendsItem;
	private MainBottomItem meItem;
	private View xiehou, baojuhua, fun_layout;

	private boolean closeApp = false;

	private boolean isTabHomeInit = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		disableReceiveALXmppEvent();
		setupView(this, getClass().getSimpleName());
		enableReceiveALXmppEvent();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context,
	 * java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarContentView(R.layout.activity_main);
		xiehou = findViewById(R.id.xiehou);
		baojuhua = findViewById(R.id.baojuhua);
		fun_layout = findViewById(R.id.fun_layout);
		buttom_content_layout = (LinearLayout) findViewById(R.id.buttom_content_layout);
		fun_layout.setOnClickListener(this);
		setViewOnclickListener(R.id.love_img, this);
		setViewOnclickListener(R.id.xiehou, this);
		setViewOnclickListener(R.id.baojuhua, this);
		setTitleButton();
		setupBottomItems();
		initBadgeView();
		initDiscoveryPopWindow();
		initFt();
		// isTabHome();
		// isTabWall();
		// isTabMessage();
		// isTabMe();
		// ft.commit();
		// mainBottomItems.get(0).performClick();

	}

	private void initFt() {
		android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
		discoveryFragment = (DiscoveryFragment) fm.findFragmentByTag("home");
		rankFragment = (RankFragment) fm.findFragmentByTag("wall");
		friendFragment = (FriendsFragment) fm.findFragmentByTag("message");
		meFragment = (MeFragment) fm.findFragmentByTag("me");
		ft = fm.beginTransaction();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// initData();
		setMeFragmentBadgeValue();
		if (currentTab == TAB_ME) {
			// 检测任务状态
			ALMissionManager.getDefaultMissionManager().checkMission();
		}
	}

	private void setTitleButton() {
		// 初始右边菜单是list列表
		BaseTitleActivityConfig config = new BaseTitleActivityConfig();
		config.rightUseImageButton(true);
		config.leftUseImageButton(true);
		setConfig(config);

		setRightButtonImageSrc(R.drawable.find_title_icon_list);
		setLeftButtonImageSrc(R.drawable.find_title_icon_shop);
		setLeftButtonClickListener(leftButtonClickListener);
		setRightButtonClickListener(rightButtonClickListener);
		setCenterLayoutClickListener(centerLayoutClickListener);
	}

	/**
	 * 初始化发现选择对话框
	 */
	private void initDiscoveryPopWindow() {
		discoverySelectView = ALLocalEnv.getLocalEnv()
				.getGlobalLayoutInflater()
				.inflate(R.layout.main_discovery_pop_layout, null);

		View v = discoverySelectView.findViewById(R.id.select_all_fl);
		v.setTag(0);
		v.setOnClickListener(popWindoClckListener);
		v = discoverySelectView.findViewById(R.id.select_female_fl);
		v.setTag(1);
		v.setOnClickListener(popWindoClckListener);
		v = discoverySelectView.findViewById(R.id.select_male_fl);
		v.setTag(2);
		v.setOnClickListener(popWindoClckListener);
		discoverySelectPopWindow = ALPopWindowUtils.createPopupWindowWithView(
				this, discoverySelectView);

		discoverySelectPopWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				// isShowIngSelectGender = false;
				exitBlur();
				invokeCenterLayoutClcik();

			}
		});
	}

	/**
	 * 创建底栏
	 */
	private void setupBottomItems() {
		for (int i = 0; i < bottomItemTxt.length; i++) {
			MainBottomItem item = new MainBottomItem(this);
			item.setItemText(bottomItemTxt[i]);
			LinearLayout.LayoutParams parm = new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f);
			parm.gravity = Gravity.BOTTOM;
			buttom_content_layout.addView(item, parm);
			item.setSelectImgRes(itemImgs[i + i], itemImgs[i + i + 1]);
			item.setItemSelected(false);
			mainBottomItems.add(item);
			if (i == 2)
				continue;

			item.setTag(i);
			item.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View view) {
					if (mBottomItemClickListener != null)
						mBottomItemClickListener.onItemClick((Integer) view
								.getTag());
				}

			});

		}

		meItem = mainBottomItems.get(TAB_ME);
		friendsItem = mainBottomItems.get(TAB_FRIEND);
	}

	/**
	 * 初始化badgeView
	 */
	private void initBadgeView() {
		// MainBottomItem friendsItem = mainBottomItems.get(TAB_FRIEND);
		// taskBadge = new BadgeView(getApplicationContext(), friendsItem);
		// taskBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
		// MainBottomItem meItem = mainBottomItems.get(TAB_ME);
		// meBadge = new BadgeView(getApplicationContext(), meItem);
		// meBadge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
		// taskBadge.show();
		// meBadge.show();

		taskBadge = new BadgeView(getApplicationContext(),
				findViewById(R.id.img_button_right));
		taskBadge.setBadgePosition(BadgeView.POSITION_TOP_LEFT);
		taskBadge.setTextSize(10);
		taskBadge.setGravity(Gravity.CENTER);
		taskBadge.setBackgroundResource(R.drawable.friend_mutual_icon_massage);

	}

	/**
	 * 切换页卡
	 * 
	 * @param pos
	 */
	private void doChangeTab(int pos) {

		if (currentTab == pos) {
			ALLog.d("页卡一致");
			return;
		}

		currentTab = pos;
		ALLog.d("页卡切换到" + currentTab);

		android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
		discoveryFragment = (DiscoveryFragment) fm.findFragmentByTag("home");
		rankFragment = (RankFragment) fm.findFragmentByTag("wall");
		friendFragment = (FriendsFragment) fm.findFragmentByTag("message");
		meFragment = (MeFragment) fm.findFragmentByTag("me");
		ft = fm.beginTransaction();

		/** 碎片管理 */

		/** 如果存在Detaches掉 */
		if (discoveryFragment != null)
			ft.hide(discoveryFragment);

		/** 如果存在Detaches掉 */
		if (rankFragment != null)
			ft.hide(rankFragment);

		/** 如果存在Detaches掉 */
		if (friendFragment != null)
			ft.hide(friendFragment);

		/** 如果存在Detaches掉 */
		if (meFragment != null)
			ft.hide(meFragment);

		taskBadge.hide();
		int title = R.string.TxtDiscovery;
		switch (pos) {
		case TAB_DISCOVERY:
			isTabHome();
			setCenterMsgDrawable(R.drawable.find_title_icon_down, RIGHT);
			setCenterLayoutClickListener(centerLayoutClickListener);
			// setRightButtonImageSrc(R.drawable.find_title_icon_pic);
			if (discoveryFragment.isShowingList()) {
				setRightButtonImageSrc(R.drawable.find_title_icon_pic);
			} else {
				setRightButtonImageSrc(R.drawable.find_title_icon_list);
			}
			break;
		case TAB_RANK:
			isTabWall();
			title = R.string.TxtRank;
			setCenterMsgDrawable(R.drawable.chat_disturb_off, NONE);
			setCenterLayoutClickListener(null);
			setRightButtonImageSrc(R.drawable.hot_title_icon_go);
			break;
		case TAB_FRIEND:
			isTabMessage();
			title = R.string.TxtFriend;
			setCenterMsgDrawable(R.drawable.chat_disturb_off, NONE);
			setCenterLayoutClickListener(null);
			if (isEditInFriend) {
				setRightButtonImageSrc(R.drawable.friend_title_icon_confirm);
			} else {
				setRightButtonImageSrc(R.drawable.friend_title_icon_edit);
			}
			break;
		case TAB_ME:
			isTabMe();
			title = R.string.TxtMe;
			setCenterMsgDrawable(R.drawable.chat_disturb_off, NONE);
			setRightButtonImageSrc(R.drawable.find_title_icon_task);
			setCenterLayoutClickListener(null);
			// resetMeFragmentBadge();
			// 检测任务状态
			ALMissionManager.getDefaultMissionManager().checkMission();
			break;
		}
		// 设置title
		setCenterTextViewMessage(title);

		ft.commit();

		// 清空粉丝提示
		resetNewFansNotice();
		// 跳转到非好友界面，清空好友界面
		if (pos != TAB_FRIEND) {
			resetNewFansListNotice();
		}
	}

	// 判断当前
	private void isTabHome() {

		if (discoveryFragment == null) {
			discoveryFragment = new DiscoveryFragment(/* discoveryUserList */);
			ft.add(R.id.realtabcontent, discoveryFragment, "home");
		} else {
			// ft.attach(discoveryFragment);
			ft.show(discoveryFragment);
			discoveryFragment.invokeChangeToTabHome("isTabHome");
		}

	}

	private void isTabWall() {
		if (rankFragment == null) {
			rankFragment = new RankFragment();
			ft.add(R.id.realtabcontent, rankFragment, "wall");
		} else {
			// ft.attach(rankFragment);
			ft.show(rankFragment);
		}
	}

	private void isTabMessage() {

		if (friendFragment == null) {
			friendFragment = new FriendsFragment();
			ft.add(R.id.realtabcontent, friendFragment, "message");
		} else {
			// ft.attach(friendFragment);
			ft.show(friendFragment);
		}
	}

	private void isTabMe() {

		if (meFragment == null) {
			meFragment = new MeFragment();
			ft.add(R.id.realtabcontent, meFragment, "me");
		} else {
			// ft.attach(meFragment);
			ft.show(meFragment);
		}
	}

	private OnClickListener popWindoClckListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			invokePopWindoClck((Integer) v.getTag());
		}
	};

	private void invokePopWindoClck(int pos) {
		discoverySelectPopWindow.dismiss();
		DiscoveryRefreshType type = DiscoveryRefreshType.TYPE_ALL;
		switch (pos) {
		case 1:
			type = DiscoveryRefreshType.TYPE_FEMALE;
			break;
		case 2:
			type = DiscoveryRefreshType.TYPE_MALE;
			break;
		}
		discoveryFragment.setRefreshType(type);
	}

	private OnClickListener leftButtonClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			invokeLetfButtonClick();
		}
	};

	private void invokeLetfButtonClick() {
		Intent i = new Intent(this, PropsActivity.class);
		startActivity(i);
	}

	/**************************************** title栏右键点击事件 *******************************************/
	private OnClickListener rightButtonClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			invokeRightButtonClcik();
		}
	};

	/**
	 * 处理title栏右键点击事件
	 */
	private void invokeRightButtonClcik() {
		switch (currentTab) {
		case TAB_DISCOVERY:
			invokeDiscoveryRightButtonClickEvent();
			break;
		case TAB_RANK:
			invokeRankRightButtonClickEvent();
			break;
		case TAB_FRIEND:
			invokeFriendRightButtonClickEvent();
			break;
		case TAB_ME:
			invokeMeRightButtonClickEvent();
			break;
		}

	}

	/**
	 * 发现页面，右键点击处理
	 */
	private void invokeDiscoveryRightButtonClickEvent() {
		if (discoveryFragment != null) {
			discoveryFragment.setShowType(!discoveryFragment.isShowingList());
			if (discoveryFragment.isShowingList()) {
				setRightButtonImageSrc(R.drawable.find_title_icon_pic);
			} else {
				setRightButtonImageSrc(R.drawable.find_title_icon_list);
			}
		}
	}

	/**
	 * 处理热榜，右键点击事件
	 */
	private void invokeRankRightButtonClickEvent() {
		Intent intent = new Intent(this, MyRankInfoActivity.class);
		startActivity(intent);
	}

	/**
	 * 处理好友，右键点击事件
	 */
	private void invokeFriendRightButtonClickEvent() {

		isEditInFriend = !isEditInFriend;
		friendFragment.onEditRequest(isEditInFriend);
		if (isEditInFriend) {
			setRightButtonImageSrc(R.drawable.friend_title_icon_confirm);
		} else {
			setRightButtonImageSrc(R.drawable.friend_title_icon_edit);
		}
	}

	/**
	 * 处理我的界面，右键点击事件
	 */
	private void invokeMeRightButtonClickEvent() {
		ALMissionManager.getDefaultMissionManager().showMissionPopWindow(
				findViewById(R.id.realtabcontent));
	}

	/**************************************** title栏右键布局点击事件 *******************************************/

	/**************************************** title栏中间布局点击事件 *******************************************/
	private OnClickListener centerLayoutClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			invokeCenterLayoutClcik();
		}
	};

	/**
	 * 处理中间布局点击
	 */
	private void invokeCenterLayoutClcik() {

		if (isShowIngSelectGender) {
			// 正在显示选择对话框，那么隐藏他
			setCenterMsgDrawable(R.drawable.find_title_icon_down, RIGHT);

		} else {
			// 没有显示对话框，显示
			setCenterMsgDrawable(R.drawable.find_title_icon_up, RIGHT);
			ALPopWindowUtils.showPopWindow(discoverySelectPopWindow,
					center_layout);
			enterBlur();

		}
		isShowIngSelectGender = !isShowIngSelectGender;
	}

	/**************************************** title栏中间布局点击事件 *******************************************/

	@Override
	public void onClick(final View v) {
		switch (v.getId()) {
		case R.id.love_img:
			invokeLoveImgClickEvent();
			break;
		case R.id.xiehou:
			inVokeXiehouClickEvent();
			break;
		case R.id.baojuhua:
			invokeBaojuhuaClickEvent();
			break;
		}
	}

	private void invokeLoveImgClickEvent() {
		if (fun_layout.getVisibility() == View.GONE) {
			showView(fun_layout);
		} else {
			goneView(fun_layout);
		}
	}

	private void inVokeXiehouClickEvent() {
		goneView(fun_layout);
		Intent i = new Intent(this, XieHouActivity.class);
		startActivity(i);
	}

	private void invokeBaojuhuaClickEvent() {
		goneView(fun_layout);
		Intent i = new Intent(this, BaoMiHuaActivity.class);
		startActivity(i);
	}

	@Override
	public void onWifiStateChangedCallback(boolean state) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDataConnectionEstablished(ALConnectionType type) {
		// TODO Auto-generated method stub
		super.onDataConnectionEstablished(type);
	}

	@Override
	public void onDataConnectionLost() {
		// TODO Auto-generated method stub
		super.onDataConnectionLost();
	}

	@Override
	public void handleConnectStateChangedEvent(ALXmppConnectionState newState,
			ALXmppConnectionState lastState) {
		// TODO Auto-generated method stub
		super.handleConnectStateChangedEvent(newState, lastState);
		String nowState = ALXmppEventNotifyManager
				.connectionState2String(newState);
	}

	@Override
	public void handleOnConflictEvent() {
		// TODO Auto-generated method stub
		super.handleOnConflictEvent();
		// 被踢下线

	}

	@Override
	public void handleConnectionLostEvent(String errorMessage) {
		// TODO Auto-generated method stub
		super.handleConnectionLostEvent(errorMessage);
		// 连接断开
	}

	@Override
	public void handleAuthFailedEvent(String errorMessage) {
		// TODO Auto-generated method stub
		super.handleAuthFailedEvent(errorMessage);
		// 账号验证失败

	}

	@Override
	public void handleLogoutEvent() {
		// TODO Auto-generated method stub
		super.handleLogoutEvent();
		// 注销成功
	}

	@Override
	public void handleLoginedEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleLoginedEvent(data);
		test();
		invokeLoginedEvent();
		// 登陆成功
		if (inited) {
			mhandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
//					if (discoveryFragment.isInited()) {
//						discoveryFragment
//								.invokeChangeToTabHome("handleLoginedEvent");
//						ALLog.d("初始化了");
//					} else {
//						ALLog.d("还未初始化");
//					}
					invokeLoginedEvent();
				}
			}, 1000);

		} else {
			ALLog.d("还未初始化");
		}

	}

	private void invokeLoginedEvent() {

		switch (currentTab) {
		case TAB_DISCOVERY:
			if (discoveryFragment != null) {
				discoveryFragment.onRefreshReq();
			}
			break;
		case TAB_RANK:
			if (rankFragment != null) {
				rankFragment.onRefreshReq();
			}
			break;
		case TAB_FRIEND:
			if (friendFragment != null) {
				friendFragment.onRefreshReq();
			}
			break;
		}

	}

	@Override
	public void handleOnNewMessageArrivedEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleOnNewMessageArrivedEvent(msg);
		handleNewMessage(msg);
	}

	@Override
	public void handleOnMessageReceiptEvent() {
		// TODO Auto-generated method stub
		super.handleOnMessageReceiptEvent();
	}

	@Override
	public void handleNewIncommingCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewIncommingCallEvent(msg);

	}

	@Override
	public void handleUserAcceptCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserAcceptCallEvent(msg);
	}

	@Override
	public void handleUserHandupEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserHandupEvent(msg);
	}

	@Override
	public void handleUserRejectCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserRejectCallEvent(msg);
	}

	/******************************* 功能处理 *************************************/
	private void handleNewMessage(ALMessage msg) {
		String txt = "";
		switch (msg.getType()) {
		case ALMessage.NEW_INCOMMING_CALL:
			txt = msg.getFromNick() + "来电";
			break;
		case ALMessage.USER_ACCEPT_CALL:
			txt = msg.getFromNick() + "接通啦";
			break;
		case ALMessage.USER_HANDUP_CALL:
			txt = msg.getFromNick() + "挂断啦";
			break;
		case ALMessage.USER_REJECT_CALL:
			txt = msg.getFromNick() + "拒绝来电";
			break;
		case ALMessage.FAVORITE_MSG:
			// 有个碉堡收藏你了
			invokeNewFansNotice(msg);
			break;
		case ALMessage.FAVORITE_DELETED_MSG:
			// 有个碉堡从他的粉丝列表中删除了你
			invokeFavoriteDeleteNotice(msg);
			break;
		case ALMessage.FANS_DELETED_MSG:
			// 有个碉堡取消收藏你了
			invokeFansGoneNotice(msg);
			break;
		default:
			txt = ("收到来自 " + msg.getFromNick() + " 的消息 " + msg.getBody());
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleAddUserFavoritesEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleAddUserFavoritesEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleAddUserFavoritesEvent(data);

		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			User tmp = (User) data.getData();
			invokeNewFriendsNotice(tmp);
		}
	}

	/******************************* 功能处理 end *************************************/

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#invokeClearActivityEnv()
	 */
	@Override
	public void invokeClearActivityEnv() {
		// TODO Auto-generated method stub
		super.invokeClearActivityEnv();
		mhandler.removeCallbacks(closeAppTask);

		// android.support.v4.app.FragmentManager fm =
		// getSupportFragmentManager();
		// discoveryFragment = (DiscoveryFragment) fm.findFragmentByTag("home");
		// rankFragment = (RankFragment) fm.findFragmentByTag("wall");
		// friendFragment = (FriendsFragment) fm.findFragmentByTag("message");
		// meFragment = (MeFragment) fm.findFragmentByTag("me");
		// ft = fm.beginTransaction();
		//
		// if (discoveryFragment != null) {
		// ft.detach(discoveryFragment);
		// }
		//
		// if (rankFragment != null) {
		// ft.detach(rankFragment);
		// }
		//
		// if (friendFragment != null) {
		// ft.detach(friendFragment);
		// }
		//
		// if (meFragment != null) {
		// ft.detach(meFragment);
		// }
		// ft.commit();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (closeApp) {
			ALLocalEnv.getLocalEnv().closeApp();
		} else {
			closeApp = true;
			Toast.makeText(getApplicationContext(),
					getString(R.string.TxtCloseAppHint), Toast.LENGTH_SHORT)
					.show();
			// 1秒后清除标志位
			mhandler.postDelayed(closeAppTask, ALTimeUtils.SECOND);
		}
		// backToSystemHome();
	}

	private Runnable closeAppTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			closeApp = false;
		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		if (!inited) {
			inited = !inited;
			ALLog.d("开始切换到发现");
			mainBottomItems.get(0).performClick();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleDiscoveryResult(com.alstudio.
	 * pojo.ALXmppEvent)
	 */
	@Override
	public void handleDiscoveryResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleDiscoveryResult(data);

		if (data.getResponseCode() == 0) {

			discoveryFragment.onDataUpdateReq(true, data.getData(),
					data.getBoolean());
		} else {

			discoveryFragment.onDataUpdateReq(false, null, data.getBoolean());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleGlobalSearchResult(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleGlobalSearchResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleGlobalSearchResult(data);
		@SuppressWarnings("unchecked")
		ArrayList<User> tmps = (ArrayList<User>) data.getData();
		ALLog.d("得到全站搜索数据类型 " + data.getStrData1() + " 大小 " + tmps.size());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleRankResult(com.alstudio.pojo.
	 * ALXmppEvent)
	 */
	@Override
	public void handleRankResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleRankResult(data);
		if (rankFragment != null) {
			rankFragment.onDataUpdateReq(data);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleFriendsListResult(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleFriendsListResult(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleFriendsListResult(data);
		if (friendFragment != null) {
			friendFragment.onDataUpdateReq(data);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleDeleteFriendsOrFans(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleDeleteFriendsOrFans(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleDeleteFriendsOrFans(data);
		if (friendFragment != null) {
			friendFragment.onDataUpdateReq(data);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleNewSystemMessageEvent(com.alstudio
	 * .module.xmpp.protocol.xmpp.packact.ALMessage)
	 */
	@Override
	public void handleNewSystemMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewSystemMessageEvent(msg);
		// 更新未读消息树
		loadMissedCountSumHistoryCount();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleNewNoteMessageEvent(com.alstudio
	 * .module.xmpp.protocol.xmpp.packact.ALMessage)
	 */
	@Override
	public void handleNewNoteMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewNoteMessageEvent(msg);
		// 更新未读消息树
		loadMissedCountSumHistoryCount();
	}

	private void test() {

		ALUiXmppRequestCreator.postALUiXmppVoipCheckHistoryDetail("305225@mk",
				ALLocalEnv.LOAD_MORE_START_INDEX + "",
				ALLocalEnv.LOAD_MORE_END_INDEX + "");

		ALUiXmppRequestCreator
				.postALUiXmppVoipDeleteCallHistoryDetail("305228@mk");

		ALMissionHttpManager mMissionManager = new ALMissionHttpManager();
		mMissionManager.checkTaskList(ALLocalEnv.getLocalEnv()
				.getVersionConfig().getMissionUrl()
				+ "/task/main");

	}

	/********************************* 粉丝 好友提示处理 ***************************************/
	/**
	 * 有新粉丝提示
	 * 
	 * @param msg
	 */
	private void invokeNewFansNotice(ALMessage msg) {
		if (friendsItem == null) {
			friendsItem = mainBottomItems.get(TAB_FRIEND);
		}
		if (currentTab != TAB_FRIEND) {
			friendsItem.increment();
		}
		if (friendFragment != null) {
			friendFragment.onNewFansAdd((User) msg.getData());
		}
	}

	/**
	 * 新粉丝跑了
	 * 
	 * @param msg
	 */
	private void invokeFansGoneNotice(ALMessage msg) {
		if (friendsItem == null) {
			friendsItem = mainBottomItems.get(TAB_FRIEND);
		}
		friendsItem.decrement();
		if (friendFragment != null) {
			friendFragment.onNewFansRemove((User) msg.getData());
		}
	}

	/**
	 * 清空新粉丝提示
	 */
	private void resetNewFansNotice() {
		if (friendsItem == null) {
			friendsItem = mainBottomItems.get(TAB_FRIEND);
		}
		friendsItem.resetBadgeValue();
	}

	/**
	 * 重置好友界面中列表上显示的新粉丝数
	 */
	private void resetNewFansListNotice() {
		if (friendFragment != null) {
			friendFragment.resetFansCountValue();
		}
	}

	/**
	 * 好友从他的粉丝列表中删除了爷
	 * 
	 * @param msg
	 */
	private void invokeFavoriteDeleteNotice(ALMessage msg) {
		if (friendFragment != null) {
			friendFragment.onFriendsRemove((User) msg.getData());
		}
	}

	/**
	 * 关注某人成功
	 */
	private void invokeNewFriendsNotice(User user) {
		if (friendFragment != null) {
			friendFragment.onFriendsAdd(user);
		}
	}

	/******************************************* 任务 *******************************************************/

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#handleMissionCompletedEvent()
	 */
	@Override
	public void handleMissionCompletedEvent() {
		// TODO Auto-generated method stub
		super.handleMissionCompletedEvent();
		// 任务完成
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleNewMissionAlertEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleNewMissionAlertEvent(ALXmppEvent event) {
		// TODO Auto-generated method stub
		super.handleNewMissionAlertEvent(event);
		// 新任务提醒
		int index = event.getIntData();
		MissionInfo info = (MissionInfo) event.getData();
		if ("1".equals(info.getStatus())) {
			// 可领取
			taskBadge.setText(R.string.BtnDone);
		} else if ("0".equals(info.getStatus())) {
			// 未完成
			taskBadge.setText("!");
		}
		if (currentTab == TAB_ME) {
			taskBadge.show(true);
		}

	}

	/************************************ voip ui事件处理 ****************************************************/
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleNewMissedCallEvent(java.lang.
	 * String)
	 */
	@Override
	public void handleNewMissedCallEvent(String callId) {
		// TODO Auto-generated method stub
		super.handleNewMissedCallEvent(callId);
		invokeMefragmentBadge();
	}

	private void invokeMefragmentBadge() {
		// if (meItem == null) {
		// meItem = mainBottomItems.get(TAB_ME);
		// }
		// meItem.increment();
		// 重新加载未读未读消息数
		loadMissedCountSumHistoryCount();

		if (meFragment != null) {
			// friendFragment.onNewFansAdd((User) msg.getData());
			meFragment.refreshNewNoticeItem();
		}
	}

	private int mMissedCallCount = 0;
	private int mMissedSystemMsgCount = 0;
	private int mMissedAudioMsgCount = 0;
	private int mNewVersionAlert = 0;

	public int getMissedCallCount() {
		return mMissedCallCount;
	}

	public int getMissedSystemMsgCount() {
		return mMissedSystemMsgCount;
	}

	public int getMissedAudioMsgCount() {
		return mMissedAudioMsgCount;
	}

	/**
	 * 设置我的标签中未接电话/未读系统消息/未读语音留言总数
	 */
	private void setMeFragmentBadgeValue() {
		loadMissedCountSumHistoryCount();
	}

	private void resetMeFragmentBadge() {
		if (meItem != null)
			meItem.resetBadgeValue();
	}

	// 讀取數據庫中未读电话总数
	private ALAsyncTaskCallback loaddMissedCountSumHistoryTaskCallback = new ALAsyncTaskCallback() {

		@Override
		public Object onTaskStart(Object obj) {
			// TODO Auto-generated method stub
			mMissedCallCount = ALLocalEnv.getLocalEnv().getDatabase()
					.getUnReadCallHistory();
			mMissedSystemMsgCount = ALLocalEnv.getLocalEnv().getDatabase()
					.getCountOfUnreadSystemMsg();
			mMissedAudioMsgCount = ALLocalEnv.getLocalEnv().getDatabase()
					.loadAllNumberOfUnreadMessageRecord();
			if (ALLocalEnv.getLocalEnv().isNewVersionAlert()) {
				mNewVersionAlert = 1;
			} else {
				mNewVersionAlert = 0;
			}
			return null;
		}

		@Override
		public Object onTaskFinish(Object obj) {
			// TODO Auto-generated method stub
			if (meItem != null)
				meItem.setBadgeValue(mMissedCallCount + mMissedSystemMsgCount
						+ mMissedAudioMsgCount + mNewVersionAlert);

			if (meFragment != null) {
				meFragment.loadNewNotice();
			}
			return null;
		}

		@Override
		public Object onTaskCancel() {
			// TODO Auto-generated method stub
			return null;
		}
	};

	/**
	 * 讀取数据库中未接电话/未读系统消息/未读语音留言
	 * 
	 * @param msg
	 */
	private void loadMissedCountSumHistoryCount() {
		ALAsycTask loaddMissedCountSumHistoryTask = new ALAsycTask(
				loaddMissedCountSumHistoryTaskCallback);
		loaddMissedCountSumHistoryTask.execute("");
	}

}
